<template>
	<view>
		<nav-bar title="请选择项目" @goBack="goBack"></nav-bar>
		<view class="contain">
			<scroll-view :style="{ height: mainHeight }" scroll-y scroll-with-animation class="left menu-scroll-view"
				:scroll-top="scrollTop" :scroll-into-view="itemId">
				<view v-for="(item, index) in rightData" :key="index" class="left-data lee-tab-item"
					@tap.stop="swichMenu(index)">
					<view class="line" :style="activeIndex === index ? 'background: #C27E15' : ''"></view>
					<view :class="['text', activeIndex === index ? 'active' : 'no-active']">
						{{ item.name }}
						<!-- <view class="tag">新</view> -->
					</view>
				</view>
			</scroll-view>
			<scroll-view :style="{ height: mainHeight }" class="right" :scroll-top="scrollRightTop" scroll-y
				scroll-with-animation @scroll="rightScroll">
				<view v-if=" isLoading" class="common-loading">
					<image class="loading-img" :src="baseIconUrl + 'icon_loading.png'" />
				</view>

				<view v-else-if="rightData.length > 0">
					<view class="rightDataBox" style="width: 100%;" v-for="(items, index) in rightData" :key="index"
						:id="'item' + index">
						<u-divider :text="items.name" :dashed="true"></u-divider>
						<view v-if="items.children==null" class="common-no-data">
							<image class="no-data-img" :src="baseImgUrl + 'img_no_project.png'" alt="" />
						</view>
						<view class="right-box" v-else v-for="(item, i) in items.children" :key="i">
							<view class="left-box" @click.stop="clickReserve(item)">
								<image class="img" :src="item.img ? item.img.split(',')[0] : ''" alt="" />
								<!-- <view class="show" v-if="item.status === 1">头衔标签</view> -->
							</view>
							<view class="right" @click.stop="clickReserve(item)">
								<view class="title">
									{{ item.itemName }}
								</view>

								<view class="des">
									<view>{{ item.method }}</view>
									<view class="detail-btn" @click.stop="clickProjectDetail(item)">详情</view>
								</view>

								<!-- <view class="red">
									<u-icon name="rmb" color="#fe4d4f" size="15"></u-icon>
									<view class="money">{{ item.preferential }}</view>
									<view class="rmb-text">{{ item.memberType === 1 ? '会员价' : '折扣价' }}</view>
								</view> -->

								<view class="gray-box">
									<view class="grey">
										<u-icon name="rmb" color="#6d6d6d" size="12"></u-icon>
										<view class="money">{{ item.price }}</view>
										<view class="rmb-text">原价</view>
									</view>
									<view class="button" @click.stop="clickReserve(item)">预约</view>
								</view>
							</view>
						</view>
					</view>
					<view class="rightDataBox1" :style="{ height: funMainHeight }" style="width: 100%;">
						<u-divider text="已经到底啦~~" :dashed="true"></u-divider>
					</view>
				</view>
				<view v-else class="common-no-data">
					<image class="no-data-img" :src="baseImgUrl + 'img_no_project.png'" alt="" />
					<view class="text">暂无项目</view>
				</view>
			</scroll-view>
		</view>
		<!-- <u-datetime-picker ref="datetimePicker" :show="datePickerShow" v-model="chooseDate" mode="datetime"
			:formatter="formatter" :visibleItemCount="9" @confirm="confirmDate" :minDate="minDate"
			@cancel="datePickerShow=false"></u-datetime-picker> -->
		<bottom-order v-if="chooseTechnician && chooseTechnician.length" :chooseData="chooseTechnician"
			:transferData="transferData" :showAddProject="false"></bottom-order>
		<you-popup :popupVisible="couponShow" :showBtn="false" popupTitle="可使用优惠券" @popupClose="couponShow = false">
			<view slot="closeIcon" class="icon" @click="couponShow=false">
				<u-icon name="close"></u-icon>
			</view>
			<view slot="popupContent" class="project-content">
				<view class="coupon-item" v-for="(item, index) in couponData.couponList" :key="index"
					:style="{ background: `url(${baseImgUrl}img_coupon_bg.png) no-repeat` }">
					<view class="coupon-name">{{ item.name }}</view>
					<view class="num-box"><text class="num">x{{item.oneGiveCount}}</text>张</view>
					<view class="type-box">{{ item.couponTypeName }}</view>
				</view>
				<view class="popup-button" @click="clickReceive">立即领取</view>
			</view>
		</you-popup>
	</view>
</template>

<script>
	import NavBar from "@/components/nav-bar"
	import Search from '@/components/search/index'
	import YouPopup from '@/components/you-popup/index'
	import BottomOrder from './components/bottomOrder'
	import api_home from '@/api/home'
	import pageConfig from '@/config'
	import {
		getToken
	} from '@/utils/auth'
	import section from "../../uni_modules/uview-ui/libs/config/props/section"
	export default {
		name: "shopDetail",
		components: {
			NavBar,
			Search,
			YouPopup,
			BottomOrder
		},
		data() {
			return {
				funMainHeight: '',
				token: getToken(),
				baseImgUrl: pageConfig.baseImgUrl,
				baseIconUrl: pageConfig.baseIconUrl,
				// activeIndex: 0,
				mainHeight: '',
				rightData: [],
				isLoading: false,
				leftData: [],
				statusBgColor: {
					1: 'background: linear-gradient(90deg, rgba(252, 120, 66, 1) 0%, rgba(254, 85, 56, 1) 100%)',
					2: 'background: rgba(201, 201, 201, 1);'
				},
				item: {
					status: 1
				},
				transferData: {},
				couponShow: false,
				couponData: [],
				chooseTechnician: [],
				// datePickerShow: false, // 时间选择框
				// chooseDate: Number(new Date()),
				// minDate: new Date().getTime(),
				chooseProject: {},
				receivedData: '',
				// mainCur: 0,
				// verticalNavTop: 0,
				// list: [{}],
				// itemScrollTopArray: [],
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0, // tab标题的滚动条旧位置
				activeIndex: 0, // 预设当前项的值
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				itemId: '', // 栏目右边scroll-view用于滚动的id
				arr: [], // 储存距离顶部高度的数组
				scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
				timer: null,
			}
		},
		onLoad(options) {
			this.mainHeight = this.$store.getters.heightData.noTabMainHeight
			// 获取传递的对象参数，使用decodeURIComponent解码，并转为对象
			if (options.transferData) {
				this.transferData = JSON.parse(decodeURIComponent(options.transferData))
			}
			this.getProjectType()
			this.getCouponCard()
		},
		onReady() {
			// 微信小程序需要用此写法
			// this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		onShow() {
			this.chooseTechnician = uni.getStorageSync('chooseTechnician')
			if (!this.transferData) {
				const params = uni.getStorageSync('transferData')
				this.transferData = JSON.parse(decodeURIComponent(params))
			}
			this.getMenuItemTop()
		},
		onUnload() {
			console.log('进入了onUnload');
			uni.removeStorageSync('chooseTechnician')
			uni.removeStorageSync('chargebackExplain')
			uni.removeStorageSync('transitionIds')
			uni.removeStorageSync('transferData')
		},
		methods: {
			goBack() {
				console.log('进入了goBack');
				uni.removeStorageSync('chooseTechnician')
				uni.removeStorageSync('chargebackExplain')
				uni.removeStorageSync('transitionIds')
				uni.removeStorageSync('transferData')
				uni.switchTab({
					url: '/pages/index'
				})
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			getProjectType() {
				const params = {
					regionId: this.transferData.regionId,
					minproIsshow: 1,
					status: 1
				}
				api_home.fetchProjectType(params).then(res => {
					if (res.code !== 200) return
					res.rows.unshift({
						typeName: '推荐类',
						id: 'appletItem'
					})
					const data = res.rows.map((item) => {
						return Object.assign({
							text: item.typeName,
							typeId: item.id,
						})
					})
					this.leftData = data
					this.getAllProject()
				})
			},
			getAllProject() {
				this.isLoading = true
				const params = {
					storeId: this.transferData.storeId,
					minProIsShow: 1,
					status: 1,
					regionId: this.transferData.regionId,
				}
				api_home.fetchAppletItem(params).then(res => {
					this.isLoading = false
					if (res.code !== 200) return
					let result = [];
					const data = res.data
					for (let key in data) {
						if (data.hasOwnProperty(key)) {
							let item = {
								name: key,
								children: data[key]
							};
							result.push(item);
						}
					}
					let mergedArray = []
					for (let key in data) {
						if (data.hasOwnProperty(key)) {
							const array = data[key];
							if (Array.isArray(array) && array.length > 0) {
								mergedArray.push(...array);
							}
						}
					}
					this.rightData = result
					let index = this.rightData[this.rightData.length - 1].children.length
					let mainHeight = Number(this.mainHeight.substring(0, 3))
					this.funMainHeight = parseFloat(mainHeight - parseInt(index * 120)) + 'px'
				}).catch(err => {
					this.isLoading = false
				})
			},
			getCouponCard() {
				const params = {
					storeId: this.transferData.storeId,
					couponTypeValue: 3,
					getPath: 2,
				}
				api_home.fetchSysCouponList(params).then(res => {
					if (res.code !== 200) return
					this.couponData = res.data
					this.couponShow = res.data.couponList.length
				})
			},
			clickReceive() {
				if (!this.token) {
					this.$tab.navigateTo('/subPages/home/login')
				} else {
					const params = {
						storeId: this.transferData.storeId,
						couponTypeValue: 3,
						getPath: 2
					}
					api_home.receiveCoupon(params).then(res => {
						if (res.code !== 200) return
						uni.showToast({
							title: '领取成功，请前往个人中心查看',
							icon: 'none'
						})
						this.couponShow = false
					})
				}
			},
			clickReserve(item) {
				const params = encodeURIComponent(JSON.stringify(this.transferData))
				const params1 = encodeURIComponent(JSON.stringify(item))
				uni.navigateTo({
					url: `/subPages/home/chooseTime?transferData=${params}&chooseProject=${params1}`
				})
			},
			clickProjectDetail(item) {
				const transferData = {
					...this.transferData,
					projectId: item.id,
					projectName: item.itemName,
					price: item.price,
					memberType: item.memberType,
					duration: item.duration
				}
				// console.log(this.transferData,'this.transferData');
				const params = encodeURIComponent(JSON.stringify(transferData))
				const itemParams = encodeURIComponent(JSON.stringify(item))
				uni.navigateTo({
					url: `/subPages/home/projectDetail?item=${itemParams}&transferData=${params}`
				})
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
						resolve();
					}).exec();
				})
			},
			getMenuItemTop() {
				new Promise(resolve => {
					let selectorQuery = uni.createSelectorQuery().in(this);
					selectorQuery.selectAll('.rightDataBox').boundingClientRect((rects) => {
						if (!rects.length) {
							setTimeout(() => {
								this.getMenuItemTop();
							}, 10);
							return;
						}
						rects.forEach((rect) => {
							this.arr.push(rect.top - 50)
							console.log(this.arr);
							resolve();
						})
					}).exec()
				})
			},
			// 设置左边菜单的滚动状态
			async leftMenuStatus(index) {
				this.activeIndex = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('lee-tab-item', 'menuItemHeight');
				}
				// 将菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
			},
			// 点击左边的栏目切换
			async swichMenu(index) {
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (index == this.activeIndex) return;
				this.scrollRightTop = this.oldScrollTop;
				this.$nextTick(function() {
					this.scrollRightTop = this.arr[index] - 50;
					this.activeIndex = index;
					this.leftMenuStatus(index);
				})
			},
			// 右边菜单滚动  如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
			async rightScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (this.timer) return;
				if (!this.menuHeight) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
				}
				setTimeout(() => { // 节流
					this.timer = null;
					let scrollHeight = e.detail.scrollTop + 90;
					const mainHeight = parseInt(this.mainHeight.split('px')[0])
					// console.log(scrollHeight, mainHeight, e.detail.scrollHeight);
					if (scrollHeight + mainHeight >= e.detail.scrollHeight) {
						this.leftMenuStatus(this.arr.length - 1);
						return
					}
					for (let i = 0; i < this.arr.length; i++) {
						let height1 = this.arr[i];
						let height2 = this.arr[i + 1];
						if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
							this.leftMenuStatus(i);
							break;
							return;
						}
					}
				}, 50)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.contain {
		display: flex;
		width: 100%;
		justify-content: space-between;
		padding: 25rpx 26rpx 0 0;
	}

	.left {
		width: 23%;
		height: 100%;
		background: #FFFFFF;
		border-radius: 21rpx 21rpx 21rpx 21rpx;
		opacity: 1;

		.left-data {
			padding: 38rpx 0;
			text-align: center;
			display: flex;

			.active {
				font-size: 30rpx;
				font-weight: 500;
				color: #333333;
			}

			.no-active {
				font-weight: 400;
				font-size: 26rpx;
				color: #666666;
			}

			.line {
				width: 9rpx;
				height: 30rpx;
				border-radius: 0rpx 0rpx 0rpx 0rpx;
				opacity: 1;
				transform: translateY(6rpx);
				margin-right: -30rpx;
			}

			.text {
				margin: 0 auto;
				display: flex;
				position: relative;
				white-space: nowrap;
				/* 防止换行 */
				overflow: hidden;
				/* 超出部分隐藏 */
				text-overflow: ellipsis;

				/* 显示省略号 */
				.tag {
					width: 35rpx;
					height: 35rpx;
					background: #FF2828;
					border-radius: 50%;
					opacity: 1;
					position: absolute;
					right: -30rpx;
					top: -15rpx;
					font-size: 19rpx;
					font-weight: 500;
					color: #FFFFFF;
					line-height: 35rpx;
				}
			}
		}
	}

	.right {
		width: 73%;

		.null {
			text-align: center;
			width: 100%;
			height: 40rpx;
			line-height: 40rpx;
		}

		.right-box {
			width: 100%;
			height: auto;
			background: #FFFFFF;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			opacity: 1;
			margin-bottom: 20rpx;
			padding: 24rpx 21rpx 23rpx 29rpx;
			display: flex;
			justify-content: space-between;

			.left-box {
				position: relative;
				width: 143rpx;
				height: 143rpx;

				.img {
					width: 143rpx;
					height: 143rpx;
					border-radius: 11rpx;
				}

				.show {
					position: absolute;
					bottom: -15rpx;
					left: 15%;
					width: 103rpx;
					height: 37rpx;
					line-height: 37rpx;
					opacity: 1;
					border-radius: 32rpx;
					background: rgba(255, 105, 40, 1);
					font-size: 20rpx;
					font-weight: 400;
					color: rgba(255, 255, 255, 1);
					text-align: center;
				}
			}

			.right {
				width: 66%;
				text-align: left;

				// height: 200rpx;
				.title {
					font-size: 30rpx;
					font-weight: 500;
					color: rgba(51, 51, 51, 1);
					margin-bottom: 12rpx;
					display: flex;

					.tag {
						width: 114rpx;
						height: 43rpx;
						opacity: 1;
						border-radius: 13rpx;
						background: rgba(255, 241, 238, 1);
						text-align: center;
						line-height: 43rpx;
						margin-left: 12rpx;
						font-size: 20rpx;
						font-weight: 400;
						color: rgba(255, 50, 5, 1);
					}
				}

				.des {
					display: flex;
					align-items: center;
					font-size: 26rpx;
					font-weight: 400;
					color: #333333;
					margin: 10rpx 0;
					overflow: hidden;
					text-overflow: ellipsis;
					-webkit-line-clamp: 2;
					/* 这个值可以根据需要修改，表示显示的行数 */
					-webkit-box-orient: vertical;

					.detail-btn {
						color: #faa040;
						margin-left: 8rpx;
					}
				}

				.red {
					display: flex;
					align-items: center;
					margin: 8rpx 0;

					.money {
						font-size: 31rpx;
						font-weight: bold;
						color: rgba(254, 77, 79, 1);
					}

					.rmb-text {
						font-size: 19rpx;
						font-weight: 400;
						color: rgba(254, 77, 79, 1);
						margin-left: 12rpx;
						// transform: translateY(10rpx);
					}
				}

				.gray-box {
					display: flex;
					justify-content: space-between;

					.grey {
						display: flex;
						align-items: center;
						color: rgba(102, 102, 102, 1);

						.money {
							font-size: 22.79rpx;
							font-weight: 400;
							// transform: translateY(7rpx);
						}

						.rmb-text {
							font-size: 18.63rpx;
							font-weight: 400;
							margin-left: 12rpx;
							// transform: translateY(5rpx);
						}
					}

					.button {
						width: 108rpx;
						height: 50rpx;
						border-radius: 38rpx 38rpx 38rpx 38rpx;
						opacity: 1;
						border: 1rpx solid #C27E15;
						text-align: center;
						line-height: 50rpx;
						font-size: 24rpx;
						font-weight: 500;
						color: #C27E15;
					}
				}
			}
		}
	}

	.project-content {
		.coupon-item {
			position: relative;
			width: 100%;
			height: 150rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			background-size: auto 150rpx !important;

			.coupon-name {
				margin-left: 50rpx;
				padding-top: 6rpx;
				font-size: 34rpx;
			}

			.num-box {
				margin-right: 32rpx;
				color: #FFF;

				.num {
					margin-right: 4rpx;
					font-size: 44rpx;
				}
			}

			.type-box {
				position: absolute;
				top: 16rpx;
				left: 14rpx;
				padding: 2rpx 16rpx;
				border-radius: 19rpx 0 19rpx 0;
				font-size: 20rpx;
				color: #FFF;
				background-color: #f0a17f;
			}
		}

		.popup-button {
			width: 100%;
			height: 90rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			margin: auto;
			border-radius: 90rpx;
			color: #FFF;
			background-color: #c27e15;
		}
	}
</style>